package com.chenxin.quartz.process.rcsTask.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WcsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.quartz.process.rcsTask.IAnalysisTaskByHkProcess;
import com.chenxin.wms.domain.AgvRouteMapEntity;
import com.chenxin.wms.domain.AgvTaskEntity;
import com.chenxin.wms.domain.WcsTaskEntity;
import com.chenxin.wms.mapper.AgvRouteMapMapper;
import com.chenxin.wms.mapper.AgvTaskMapper;
import com.chenxin.wms.mapper.WcsTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 解析主任务并生成AGV搬送任务
 */
@Service
public class AnalysisTaskByHkProcess implements IAnalysisTaskByHkProcess {
    @Autowired
    private WcsTaskMapper wcsTaskMapper;
    @Autowired
    private AgvTaskMapper agvTaskMapper;
    @Autowired
    private AgvRouteMapMapper agvRouteMapMapper;

    @Override
    public ProcResult call(String dvcNo, long creator) {
        // 根据设备编号判断是否有可解析的任务（按任务优先级、任务类型、创建时间等进行按序解析）
        QueryWrapper<WcsTaskEntity> iniTaskQW = new QueryWrapper<>();
        iniTaskQW.lambda().eq(WcsTaskEntity::getDvcNo, dvcNo)
                .eq(WcsTaskEntity::getTrkStatus, 0)
                .last("order by create_date limit 1");
        WcsTaskEntity wcsTrk = wcsTaskMapper.selectOne(iniTaskQW);
        if (wcsTrk == null) {
            return ProcResult.success("设备【" + dvcNo + "】无待解析任务");
        }
        // 对可解析任务进行处理(判断任务是否重复解析、生成对应小车搬送任务)
        QueryWrapper<AgvTaskEntity> repeatTaskQW = new QueryWrapper<>();
        repeatTaskQW.lambda().eq(AgvTaskEntity::getTrkId, wcsTrk.getTrkId())
                .lt(AgvTaskEntity::getAgvStatus, WcsConstants.TRK_STATUS_CANCEL).last("limit 1");
        AgvTaskEntity repeatTask = agvTaskMapper.selectOne(repeatTaskQW);
        if (repeatTask != null) {
            // 更新设备任务为异常9，并记录异常原因为重复解析
            wcsTrk.setTrkStatus(WcsConstants.TRK_STATUS_ERROR);
            wcsTrk.setComments("重复解析！【agv_task_hk】中已存在相同搬送任务");
            wcsTrk.setUpdater(creator);
            wcsTrk.setUpdateDate(new Date());
            wcsTaskMapper.updateById(wcsTrk);
            return ProcResult.error("analysis_err#001", "设备【" + dvcNo + "】解析任务【" + wcsTrk.getTrkId() + "】失败！【agv_task_hk】中已存在相同搬送任务");
        }
        // 判断相关任务模板是否正常配置
        QueryWrapper<AgvRouteMapEntity> routeMapQW = new QueryWrapper<>();
        routeMapQW.lambda().eq(AgvRouteMapEntity::getFromPosition, wcsTrk.getFrmPos())
                .eq(AgvRouteMapEntity::getToPosition, wcsTrk.getToPos())
                .eq(AgvRouteMapEntity::getDvcNo, dvcNo)
                .eq(AgvRouteMapEntity::getTrkType, wcsTrk.getTrkType()).last("limit 1");
        AgvRouteMapEntity agvRouteMap = agvRouteMapMapper.selectOne(routeMapQW);
        if (agvRouteMap == null) {
            wcsTrk.setTrkStatus(WcsConstants.TRK_STATUS_ERROR);
            wcsTrk.setComments("设备【" + dvcNo + "】的任务【" + wcsTrk.getTrkId() + "】尚未在【agv_route_map】中配置路线");
            wcsTrk.setUpdater(creator);
            wcsTrk.setUpdateDate(new Date());
            wcsTaskMapper.updateById(wcsTrk);
            return ProcResult.error(WcsConstants.PROC_CODE_ERROR, "设备【" + dvcNo + "】的任务【" + wcsTrk.getTrkId() + "】尚未在【agv_route_map】中配置路线");
        }
        // 生成对应的小车搬送任务
        AgvTaskEntity agvTask = new AgvTaskEntity();
        agvTask.setTrkId(wcsTrk.getTrkId());
        agvTask.setCtnrCode(wcsTrk.getContNo());
        agvTask.setCtnrTyp(wcsTrk.getContType());
        agvTask.setTaskCode(String.valueOf(System.currentTimeMillis()));
        agvTask.setReqCode(wcsTrk.getContNo() + System.currentTimeMillis());
        agvTask.setPriority(WcsConstants.TASK_PRIORITY_NORMAL);
        agvTask.setTaskTyp(agvRouteMap.getTaskTyp());
        agvTask.setPositionCodePath(agvRouteMap.getPositionPath());
        agvTask.setCreator(creator);
        agvTask.setCreateDate(new Date());
        // 将新任务写入数据库
        agvTaskMapper.insert(agvTask);
        // 更新设备任务为执行中
        wcsTrk.setTrkStatus(WcsConstants.TRK_STATUS_RUNNING);
        wcsTrk.setComments("解析成功，生成AGV搬送任务【" + agvTask.getAgvId() + "】");
        wcsTrk.setUpdater(creator);
        wcsTrk.setUpdateDate(new Date());
        wcsTaskMapper.updateById(wcsTrk);
        return ProcResult.success("设备【" + dvcNo + "】解析任务【" + wcsTrk.getTrkId() + "】成功");
    }
}
